home *** CD-ROM | disk | FTP | other *** search
/ Developer CD Series 1992 June: ROMin Holiday / ADC Developer CD (1992-06) (''ROMin Holiday'')_iso / Developer Connection - 06-1992.iso / Periodicals / develop / develop 1 code / Offscreen / Sample.spotlight / Sample.p < prev    next >
Encoding:
Text File  |  1989-06-19  |  31.7 KB  |  906 lines  |  [TEXT/MPS ]

  1. {------------------------------------------------------------------------------
  2. #
  3. #    Apple Macintosh Developer Technical Support
  4. #
  5. #    MultiFinder-Aware Simple Sample Application
  6. #
  7. #    Sample
  8. #
  9. #    Sample.p    -    Pascal Source
  10. #
  11. #    Copyright © 1989 Apple Computer, Inc.
  12. #    All rights reserved.
  13. #
  14. #    Versions:    
  15. #                1.00                08/88
  16. #                1.01                11/88
  17. #                1.02                04/89    MPW 3.1
  18. #
  19. #    Components:
  20. #                Sample.p            April 1, 1989
  21. #                Sample.c            April 1, 1989
  22. #                Sample.a            April 1, 1989
  23. #                Sample.inc1.a        April 1, 1989
  24. #                SampleMisc.a        April 1, 1989
  25. #                Sample.r            April 1, 1989
  26. #                Sample.h            April 1, 1989
  27. #                [P]Sample.make        April 1, 1989
  28. #                [C]Sample.make        April 1, 1989
  29. #                [A]Sample.make        April 1, 1989
  30. #
  31. #    Sample is an example application that demonstrates how to
  32. #    initialize the commonly used toolbox managers, operate 
  33. #    successfully under MultiFinder, handle desk accessories, 
  34. #    and create, grow, and zoom windows.
  35. #
  36. #    It does not by any means demonstrate all the techniques 
  37. #    you need for a large application. In particular, Sample 
  38. #    does not cover exception handling, multiple windows/documents, 
  39. #    sophisticated memory management, printing, or undo. All of 
  40. #    these are vital parts of a normal full-sized application.
  41. #
  42. #    This application is an example of the form of a Macintosh 
  43. #    application; it is NOT a template. It is NOT intended to be 
  44. #    used as a foundation for the next world-class, best-selling, 
  45. #    600K application. A stick figure drawing of the human body may 
  46. #    be a good example of the form for a painting, but that does not 
  47. #    mean it should be used as the basis for the next Mona Lisa.
  48. #
  49. #    We recommend that you review this program or TESample before 
  50. #    beginning a new application.
  51. #
  52. ------------------------------------------------------------------------------}
  53.  
  54.  
  55. PROGRAM Sample;
  56.  
  57.  
  58. {Segmentation strategy:
  59.  
  60.  This program consists of three segments. Main contains most of the code,
  61.  including the MPW libraries, and the main program. Initialize contains
  62.  code that is only used once, during startup, and can be unloaded after the
  63.  program starts. %A5Init is automatically created by the Linker to initialize
  64.  globals for the MPW libraries and is unloaded right away.}
  65.  
  66.  
  67. {SetPort strategy:
  68.  
  69.  Toolbox routines do not change the current port. In spite of this, in this
  70.  program we use a strategy of calling SetPort whenever we want to draw or
  71.  make calls which depend on the current port. This makes us less vulnerable
  72.  to bugs in other software which might alter the current port (such as the
  73.  bug (feature?) in many desk accessories which change the port on OpenDeskAcc).
  74.  Hopefully, this also makes the routines from this program more self-contained,
  75.  since they don't depend on the current port setting.}
  76.  
  77.  
  78. USES
  79.     MemTypes, QuickDraw, OSIntf, ToolIntf, PackIntf, Traps;
  80.  
  81. CONST
  82.     {MPW 3.0 will include a Traps.p interface file that includes constants for trap numbers.
  83.      These constants are from that file.}
  84.     {1.02 - since using MPW 3.0 only, we include Traps.p, so we now have trap numbers.}
  85.  
  86.     {1.01 - changed constants to begin with 'k' for consistency, except for resource IDs}
  87.     {SysEnvironsVersion is passed to SysEnvirons to tell it which version of the
  88.      SysEnvRec we understand.}
  89.     kSysEnvironsVersion        = 1;
  90.  
  91.     {OSEvent is the event number of the suspend/resume and mouse-moved events sent
  92.      by MultiFinder. Once we determine that an event is an osEvent, we look at the
  93.      high byte of the message sent to determine which kind it is. To differentiate
  94.      suspend and resume events we check the resumeMask bit.}
  95.     kOSEvent                = app4Evt;    {event used by MultiFinder}
  96.     kSuspendResumeMessage    = 1;        {high byte of suspend/resume event message}
  97.     kResumeMask                = 1;        {bit of message field for resume vs. suspend}
  98.     kNoEvents                = 0;        {no events mask}
  99.  
  100.     {1.01 - kMinHeap - This is the minimum result from the following
  101.      equation:
  102.             
  103.             ORD(GetApplLimit) - ORD(ApplicZone)
  104.             
  105.      for the application to run. It will insure that enough memory will
  106.      be around for reasonable-sized scraps, FKEYs, etc. to exist with the
  107.      application, and still give the application some 'breathing room'.
  108.      To derive this number, we ran under a MultiFinder partition that was
  109.      our requested minimum size, as given in the 'SIZE' resource.}
  110.      
  111.     kMinHeap    = 21 * 1024;
  112.     
  113.     {1.01 - kMinSpace - This is the minimum result from PurgeSpace, when called
  114.      at initialization time, for the application to run. This number acts
  115.      as a double-check to insure that there really is enough memory for the
  116.      application to run, including what has been taken up already by
  117.      pre-loaded resources, the scrap, code, and other sundry memory blocks.}
  118.      
  119.     kMinSpace    = 8 * 1024;
  120.     
  121.     {kExtremeNeg and kExtremePos are used to set up wide open rectangles and regions.}
  122.     kExtremeNeg    = -32768;
  123.     kExtremePos    = 32767 - 1;            {required for old region bug}
  124.     
  125.     {The following constants are all resource IDs, corresponding to resources in Sample.r.}
  126.     rMenuBar    = 128;                    {application's menu bar}
  127.     rAboutAlert    = 128;                    {about alert}
  128.     rUserAlert    = 129;                    {error user alert}
  129.     rWindow        = 128;                    {application's window}
  130.     rStopRect    = 128;                    {rectangle for Stop light}
  131.     rGoRect        = 129;                    {rectangle for Go light}
  132.  
  133.     {The following constants are used to identify menus and their items. The menu IDs
  134.      have an "m" prefix and the item numbers within each menu have an "i" prefix.}
  135.     mApple        = 128;                    {Apple menu}
  136.     iAbout        = 1;
  137.  
  138.     mFile        = 129;                    {File menu}
  139.     iNew        = 1;
  140.     iClose        = 4;
  141.     iQuit        = 12;
  142.  
  143.     mEdit        = 130;                    {Edit menu}
  144.     iUndo        = 1;
  145.     iCut        = 3;
  146.     iCopy        = 4;
  147.     iPaste        = 5;
  148.     iClear        = 6;
  149.  
  150.     mLight        = 131;                    {Light menu}
  151.     iStop        = 1;
  152.     iGo            = 2;
  153.     
  154.     {1.01 - kDITop and kDILeft are used to locate the Disk Initialization dialogs.}
  155.     kDITop        = $0050;
  156.     kDILeft        = $0070;
  157.  
  158.  
  159. VAR
  160.     {The "g" prefix is used to emphasize that a variable is global.}
  161.  
  162.     {GMac is used to hold the result of a SysEnvirons call. This makes
  163.      it convenient for any routine to check the environment. It is
  164.      global information, anyway.}
  165.     gMac                : SysEnvRec;    {set up by Initialize}
  166.  
  167.     {GHasWaitNextEvent is set at startup, and tells whether the WaitNextEvent
  168.      trap is available. If it is false, we know that we must call GetNextEvent.}
  169.     gHasWaitNextEvent    : BOOLEAN;        {set up by Initialize}
  170.  
  171.     {GInBackground is maintained by our osEvent handling routines. Any part of
  172.      the program can check it to find out if it is currently in the background.}
  173.     gInBackground        : BOOLEAN;        {maintained by Initialize and DoEvent}
  174.  
  175.  
  176.     {The following globals are the state of the window. If we supported more than
  177.      one window, they would be attatched to each document, rather than globals.}
  178.  
  179.     {GStopped tells whether the stop light is currently on stop or go.}
  180.     gStopped            : BOOLEAN;        {maintained by Initialize and SetLight}
  181.  
  182.     {GStopRect and gGoRect are the rectangles of the two stop lights in the window.}
  183.     gStopRect            : Rect;            {set up by Initialize}
  184.     gGoRect                : Rect;            {set up by Initialize}
  185.  
  186.  
  187. {$S Initialize}
  188. FUNCTION TrapAvailable(tNumber: INTEGER; tType: TrapType): BOOLEAN;
  189.  
  190. {Check to see if a given trap is implemented. This is only used by the
  191.  Initialize routine in this program, so we put it in the Initialize segment.
  192.  The recommended approach to see if a trap is implemented is to see if
  193.  the address of the trap routine is the same as the address of the
  194.  Unimplemented trap.}
  195. {1.02 - Needs to be called after call to SysEnvirons so that it can check
  196.  if a ToolTrap is out of range of a pre-MacII ROM.}
  197.  
  198. BEGIN
  199.     IF (tType = ToolTrap) &
  200.         (gMac.machineType > envMachUnknown) &
  201.         (gMac.machineType < envMacII) THEN BEGIN        {it's a 512KE, Plus, or SE}
  202.         tNumber := BAND(tNumber, $03FF);
  203.         IF tNumber > $01FF THEN                            {which means the tool traps}
  204.             tNumber := _Unimplemented;                    {only go to $01FF}
  205.     END;
  206.     TrapAvailable := NGetTrapAddress(tNumber, tType) <>
  207.                         GetTrapAddress(_Unimplemented);
  208. END; {TrapAvailable}
  209.  
  210.  
  211. {$S Main}
  212. FUNCTION IsDAWindow(window: WindowPtr): BOOLEAN;
  213.  
  214. {Check if a window belongs to a desk accessory.}
  215.  
  216. BEGIN
  217.     IF window = NIL THEN
  218.         IsDAWindow := FALSE
  219.     ELSE    {DA windows have negative windowKinds}
  220.         IsDAWindow := WindowPeek(window)^.windowKind < 0;
  221. END; {IsDAWindow}
  222.  
  223.  
  224. {$S Main}
  225. FUNCTION IsAppWindow(window: WindowPtr): BOOLEAN;
  226.  
  227. {Check to see if a window belongs to the application. If the window pointer
  228.  passed was NIL, then it could not be an application window. WindowKinds
  229.  that are negative belong to the system and windowKinds less than userKind
  230.  are reserved by Apple except for windowKinds equal to dialogKind, which
  231.  mean it is a dialog.
  232.  1.02 - In order to reduce the chance of accidentally treating some window
  233.  as an AppWindow that shouldn't be, we'll only return true if the windowkind
  234.  is userKind. If you add different kinds of windows to Sample you'll need
  235.  to change how this all works.}
  236.  
  237. BEGIN
  238.     IF window = NIL THEN
  239.         IsAppWindow := FALSE
  240.     ELSE    {application windows have windowKinds = userKind (8)}
  241.         WITH WindowPeek(window)^ DO
  242.             IsAppWindow := (windowKind = userKind);
  243. END; {IsAppWindow}
  244.  
  245.  
  246. {$S Main}
  247. PROCEDURE AlertUser;
  248.  
  249. {Display an alert that tells the user an error occurred, then exit the program.
  250.  This routine is used as an ultimate bail-out for serious errors that prohibit
  251.  the continuation of the application. Errors that do not require the termination
  252.  of the application should be handled in a different manner. Error checking and
  253.  reporting has a place even in the simplest application. For simplicity, the alert
  254.  displayed here only says that an error occurred, but not what it was. There are
  255.  various methods available for being more specific.}
  256.  
  257. VAR
  258.     itemHit    : INTEGER;
  259. BEGIN
  260.     SetCursor(arrow);
  261.     itemHit := Alert(rUserAlert, NIL);
  262.     ExitToShell;
  263. END; {AlertUser}
  264.  
  265.  
  266. {$S Main}
  267. FUNCTION DoCloseWindow(window: WindowPtr) : BOOLEAN;
  268.  
  269. {Close a window.}
  270.  
  271. {1.01 - At this point, if there was a document associated with a
  272.  window, you could do any document saving processing if it is 'dirty'.
  273.  DoCloseWindow would return TRUE if the window actually closes, i.e.,
  274.  the user does not cancel from a save dialog. This result is handy when
  275.  the user quits an application, but then cancels a save of a document
  276.  associated with a window. We also added code to close the application
  277.  window since otherwise, the termination routines would never stop looping,
  278.  waiting for FrontWindow to return NIL.}
  279.  
  280. BEGIN
  281.     DoCloseWindow := TRUE;
  282.     IF IsDAWindow(window) THEN
  283.         CloseDeskAcc(WindowPeek(window)^.windowKind);
  284.     IF IsAppWindow(window) THEN
  285.         CloseWindow(window);
  286. END; {DoCloseWindow}
  287.  
  288.  
  289. {$S Initialize}
  290. FUNCTION GoGetRect(rectID: INTEGER; VAR theRect: Rect) : BOOLEAN;
  291.  
  292. {This utility loads the global rectangles that are used by the window
  293.  drawing routines. It shows how the resource manager can be used to hold
  294.  values in a convenient manner. These values are then easily altered without
  295.  having to re-compile the source code. In this particular case, we know
  296.  that this routine is being called at initialization time. Therefore,
  297.  if this returns FALSE, we will assume that the application is in such
  298.  bad shape that we should just exit. Your error handling may differ, but
  299.  the check should still be made.}
  300.  
  301. {1.01 - Changed GoGetRect to return a BOOLEAN that indicates if it was successful
  302.  in getting the rectangle rather than just doing ExitToShell.}
  303.  
  304. TYPE
  305.     RectPtr        = ^Rect;
  306.     RectHnd        = ^RectPtr;
  307. VAR
  308.     resource    : Handle;
  309. BEGIN
  310.     resource := GetResource('RECT', rectID);
  311.     IF resource <> NIL THEN BEGIN
  312.         GoGetRect := TRUE;
  313.         theRect := RectHnd(resource)^^;
  314.         END
  315.     ELSE
  316.         GoGetRect := FALSE;
  317. END; {GoGetRect}
  318.  
  319.  
  320. {$S Initialize}
  321. PROCEDURE Initialize;
  322.  
  323. {Set up the whole world, including global variables, Toolbox managers,
  324.  and menus. We also create our one application window at this time.
  325.  Since window storage is non-relocateable, how and when to allocate space
  326.  for windows is very important so that heap fragmentation does not occur.
  327.  Because Sample has only one window and it is only disposed when the application
  328.  quits, we will allocate its space here, before anything that might be a locked
  329.  relocatable object gets into the heap. This way, we can force its storage to be
  330.  in the lowest memory available in the heap. Window storage can differ widely
  331.  amongst applications depending on how many windows are created and disposed.
  332.  If a failure occurs here, we will consider that the application is in such
  333.  bad shape that we should just exit. Your error handling may differ, but
  334.  the checks should still be made.}
  335.  
  336. {1.01 - The code that used to be part of ForceEnvirons has been moved into
  337.  this module. If an error is detected, instead of merely doing an ExitToShell,
  338.  which leaves the user without much to go on, we call AlertUser, which puts
  339.  up a simple alert that just says an error occurred and then calls ExitToShell.
  340.  In the interests of keeping things simple, the alert does not state the specific
  341.  cause of the error, but a more informative alert would be appropriate for more
  342.  sophisticated applications. Since there is no other cleanup needed at this point
  343.  if an error is detected, this form of error- handling is acceptable. If more
  344.  sophisticated error recovery is needed, a signal mechanism, such as is provided
  345.  by Signals, can be used.}
  346.  
  347. VAR
  348.     menuBar            : Handle;
  349.     window            : WindowPtr;
  350.     ignoreError        : OSErr;
  351.     total, contig    : LongInt;
  352.     ignoreResult    : BOOLEAN;
  353.     event            : EventRecord;
  354.     count            : INTEGER;
  355.  
  356. BEGIN
  357.     gInBackground := FALSE;
  358.  
  359.     InitGraf(@thePort);
  360.     InitFonts;
  361.     InitWindows;
  362.     InitMenus;
  363.     TEInit;
  364.     InitDialogs(NIL);
  365.     InitCursor;
  366.     
  367.     {Call MPPOpen and ATPLoad at this point to initialize AppleTalk,
  368.      if you are using it.}
  369.     {NOTE -- It is no longer necessary, and actually unhealthy, to check
  370.      PortBUse and SPConfig before opening AppleTalk. The drivers are capable
  371.      of checking for port availability themselves.}
  372.     
  373.     {This next bit of code is necessary to allow the default button of our
  374.      alert be outlined.
  375.      1.02 - Changed to call EventAvail so that we don't lose some important
  376.      events.}
  377.      
  378.     FOR count := 1 TO 3 DO
  379.         ignoreResult := EventAvail(everyEvent, event);
  380.     
  381.     {Ignore the error returned from SysEnvirons; even if an error occurred,
  382.      the SysEnvirons glue will fill in the SysEnvRec. You can save a redundant
  383.      call to SysEnvirons by calling it after initializing AppleTalk.}
  384.      
  385.     ignoreError := SysEnvirons(kSysEnvironsVersion, gMac);
  386.     
  387.     {Make sure that the machine has at least 128K ROMs. If it doesn't, exit.}
  388.     
  389.     IF gMac.machineType < 0 THEN AlertUser;
  390.     
  391.     {1.02 - Move TrapAvailable call to after SysEnvirons so that we can tell
  392.      in TrapAvailable if a tool trap value is out of range.}
  393.      
  394.     gHasWaitNextEvent := TrapAvailable(_WaitNextEvent, ToolTrap);
  395.  
  396.     {1.01 - We used to make a check for memory at this point by examining ApplLimit,
  397.      ApplicZone, and StackSpace and comparing that to the minimum size we told
  398.      MultiFinder we needed. This did not work well because it assumed too much about
  399.      the relationship between what we asked MultiFinder for and what we would actually
  400.      get back, as well as how to measure it. Instead, we will use an alternate
  401.      method comprised of two steps.}
  402.      
  403.     {It is better to first check the size of the application heap against a value
  404.      that you have determined is the smallest heap the application can reasonably
  405.      work in. This number should be derived by examining the size of the heap that
  406.      is actually provided by MultiFinder when the minimum size requested is used.
  407.      The derivation of the minimum size requested from MultiFinder is described
  408.      in Sample.h. The check should be made because the preferred size can end up
  409.      being set smaller than the minimum size by the user. This extra check acts to
  410.      insure that your application is starting from a solid memory foundation.}
  411.      
  412.     IF ORD(GetApplLimit) - ORD(ApplicZone) < kMinHeap THEN AlertUser;
  413.     
  414.     {Next, make sure that enough memory is free for your application to run. It
  415.      is possible for a situation to arise where the heap may have been of required
  416.      size, but a large scrap was loaded which left too little memory. To check for
  417.      this, call PurgeSpace and compare the result with a value that you have determined
  418.      is the minimum amount of free memory your application needs at initialization.
  419.      This number can be derived several different ways. One way that is fairly
  420.      straightforward is to run the application in the minimum size configuration
  421.      as described previously. Call PurgeSpace at initialization and examine the value
  422.      returned. However, you should make sure that this result is not being modified
  423.      by the scrap's presence. You can do that by calling ZeroScrap before calling
  424.      PurgeSpace. Make sure to remove that call before shipping, though.}
  425.      
  426.     PurgeSpace(total, contig);
  427.     IF total < kMinSpace THEN AlertUser;
  428.  
  429.     {The extra benefit to waitng until after the Toolbox Managers have been initialized
  430.      before checking memory is that we can now give the user an alert to tell him what
  431.      happened. Although it is possible that the memory situation could be worsened by
  432.      displaying an alert, MultiFinder would gracefully exit the application with
  433.      an informative alert if memory became critical. Here we are acting more
  434.      in a preventative manner to avoid future disaster from low-memory problems.}
  435.      
  436.     {We will allocate our own window storage instead of letting the Window
  437.      Manager for two reasons. One, GetNewWindow locks the 'WIND' resource
  438.      handle before calling NewWindow and this can lead to heap fragmentation.
  439.      Two, it takes just as much time for NewWindow to get the memory as it
  440.      does for us to get it.}
  441.  
  442.     window := WindowPtr(NewPtr(SIZEOF(WindowRecord)));
  443.     IF window = NIL THEN AlertUser;
  444.     window := GetNewWindow(rWindow, Ptr(window), WindowPtr(-1));
  445.  
  446.     menuBar := GetNewMBar(rMenuBar);        {read menus into menu bar}
  447.     IF menuBar = NIL THEN AlertUser;
  448.     SetMenuBar(menuBar);                    {install menus}
  449.     DisposHandle(menuBar);
  450.     AddResMenu(GetMHandle(mApple), 'DRVR');    {add DA names to Apple menu}
  451.     DrawMenuBar;
  452.  
  453.     gStopped := TRUE;
  454.     IF NOT GoGetRect(rStopRect, gStopRect) THEN
  455.         AlertUser;                            {the stop light rectangle}
  456.     IF NOT GoGetRect(rGoRect, gGoRect) THEN
  457.         AlertUser;                            {the go light rectangle}
  458. END; {Initialize}
  459.  
  460.  
  461. (**************************************************************************************
  462. 1.01 - PROCEDURE DoCloseBehind(window: WindowPtr); was removed.
  463.  
  464. {1.01 - DoCloseBehind was a good idea for closing windows when quitting
  465.  and not having to worry about updating the windows, but it suffered
  466.  from a fatal flaw. If a desk accessory owned two windows, it would
  467.  close both those windows when CloseDeskAcc was called. When DoCloseBehind
  468.  got around to calling DoCloseWindow for that other window that was already
  469.  closed, things would go very poorly. Another option would be to have a
  470.  procedure, GetRearWindow, that would go through the window list and return
  471.  the last window. Instead, we decided to present the standard approach
  472.  of getting and closing FrontWindow until FrontWindow returns NIL. This
  473.  has a potential benefit in that the window whose document needs to be saved
  474.  may be visible since it is the front window, therefore decreasing the
  475.  chance of user confusion. For aesthetic reasons, the windows in the
  476.  application should be checked for updates periodically and have the
  477.  updates serviced.}
  478. **************************************************************************************)
  479.  
  480.  
  481. {$S Main}
  482. PROCEDURE Terminate;
  483.  
  484. {Clean up the application and exits. We close all of the windows so that
  485.  they can update their documents, if any.}
  486.  
  487. {1.01 - If we find out that a cancel has occurred, we won't exit to the
  488.  shell, but will return instead.}
  489.  
  490. VAR
  491.     aWindow    : WindowPtr;
  492.     closed    : BOOLEAN;
  493.  
  494. BEGIN
  495.     closed := TRUE;
  496.     REPEAT
  497.         aWindow := FrontWindow;                    {get the current front window}
  498.         IF aWindow <> NIL THEN
  499.             closed := DoCloseWindow(aWindow);    {close this window}
  500.     UNTIL (NOT closed) | (aWindow = NIL);        {do all windows}
  501.     IF closed THEN
  502.         ExitToShell;                            {exit if no cancellation}
  503. END; {Terminate}
  504.  
  505.  
  506. {$S Main}
  507. PROCEDURE SetLight(window: WindowPtr; newStopped: BOOLEAN);
  508.  
  509. {Change the setting of the light.}
  510.  
  511. BEGIN
  512.     IF newStopped <> gStopped THEN BEGIN
  513.         gStopped := newStopped;
  514.         SetPort(window);
  515.         InvalRect(window^.portRect);
  516.     END;
  517. END; {SetLight}
  518.  
  519.  
  520. {$S Main}
  521. PROCEDURE AdjustMenus;
  522.  
  523. {Enable and disable menus based on the current state.
  524.  The user can only select enabled menu items. We set up all the menu items
  525.  before calling MenuSelect or MenuKey, since these are the only times that
  526.  a menu item can be selected. Note that MenuSelect is also the only time
  527.  the user will see menu items. This approach to deciding what enable/
  528.  disable state a menu item has the advantage of concentrating all the decision-
  529.  making in one routine, as opposed to being spread throughout the application.
  530.  Other application designs may take a different approach that may or may not be
  531.  just as valid.}
  532.  
  533. VAR
  534.     window            : WindowPtr;
  535.     menu            : MenuHandle;
  536.  
  537. BEGIN
  538.     window := FrontWindow;
  539.  
  540.     menu := GetMHandle(mFile);
  541.     IF IsDAWindow(window) THEN                {we can allow desk accessories to be closed from the menu}
  542.         EnableItem(menu, iClose)
  543.     ELSE
  544.         DisableItem(menu, iClose);            {but not our traffic light window}
  545.  
  546.     menu := GetMHandle(mEdit);
  547.     IF IsDAWindow(window) THEN BEGIN        {a desk accessory might need the edit menu}
  548.         EnableItem(menu, iUndo);
  549.         EnableItem(menu, iCut);
  550.         EnableItem(menu, iCopy);
  551.         EnableItem(menu, iPaste);
  552.         EnableItem(menu, iClear);
  553.     END ELSE BEGIN                            {but we know we do not}
  554.         DisableItem(menu, iUndo);
  555.         DisableItem(menu, iCut);
  556.         DisableItem(menu, iCopy);
  557.         DisableItem(menu, iClear);
  558.         DisableItem(menu, iPaste);
  559.     END;
  560.  
  561.     menu := GetMHandle(mLight);
  562.     IF IsAppWindow(window) THEN BEGIN        {we know that it must be the traffic light}
  563.         EnableItem(menu, iStop);
  564.         EnableItem(menu, iGo);
  565.     END ELSE BEGIN
  566.         DisableItem(menu, iStop);
  567.         DisableItem(menu, iGo);
  568.     END;
  569.     CheckItem(menu, iStop, gStopped);        {we can also determine check/uncheck state, too}
  570.     CheckItem(menu, iGo, NOT gStopped);
  571. END; {AdjustMenus}
  572.  
  573.  
  574. {$S Main}
  575. PROCEDURE DoMenuCommand(menuResult: LONGINT);
  576.  
  577. {This is called when an item is chosen from the menu bar (after calling
  578.  MenuSelect or MenuKey). It performs the right operation for each command.
  579.  It is good to have both the result of MenuSelect and MenuKey go to
  580.  one routine like this to keep everything organized.}
  581.  
  582. VAR
  583.     menuID            : INTEGER;        {the resource ID of the selected menu}
  584.     menuItem        : INTEGER;        {the item number of the selected menu}
  585.     itemHit            : INTEGER;
  586.     daName            : Str255;
  587.     daRefNum        : INTEGER;
  588.     handledByDA        : BOOLEAN;
  589.     ignore            : BOOLEAN;
  590.  
  591. BEGIN
  592.     menuID := HiWrd(menuResult);    {use built-ins (for efficiency)...}
  593.     menuItem := LoWrd(menuResult);    {to get menu item number and menu number}
  594.     CASE menuID OF
  595.         mApple:
  596.             CASE menuItem OF
  597.                 iAbout:                {bring up alert for About}
  598.                     itemHit := Alert(rAboutAlert, NIL);
  599.                 OTHERWISE BEGIN        {all non-About items in this menu are DAs}
  600.                     GetItem(GetMHandle(mApple), menuItem, daName);
  601.                     daRefNum := OpenDeskAcc(daName);
  602.                 END;
  603.             END;
  604.         mFile:
  605.             CASE menuItem OF
  606.                 iClose:
  607.                     ignore := DoCloseWindow(FrontWindow); {we don't care if cancelled}
  608.                 iQuit:
  609.                     Terminate;
  610.             END;
  611.         mEdit:                        {call SystemEdit for DA editing & MultiFinder}
  612.             handledByDA := SystemEdit(menuItem-1);    {since we don't do any editing}
  613.         mLight:
  614.             CASE menuItem OF
  615.                 iStop:
  616.                     SetLight(FrontWindow, TRUE);
  617.                 iGo:
  618.                     SetLight(FrontWindow, FALSE);
  619.             END;
  620.     END;
  621.     HiliteMenu(0);                    {unhighlight what MenuSelect (or MenuKey) hilited}
  622. END; {DoMenuCommand}
  623.  
  624.  
  625. {$S Main}
  626. PROCEDURE DrawWindow(window: WindowPtr);
  627.  
  628. {Draw the contents of the application window. We do some drawing in color, using
  629.  Classic QuickDraw's color capabilities. This will be black and white on old
  630.  machines, but color on color machines. At this point, the window's visRgn is
  631.  set to allow drawing only where it needs to be done.}
  632.  
  633. BEGIN
  634.     SetPort(window);
  635.  
  636.     EraseRect(window^.portRect);    {clear out any garbage that might be left behind}
  637.     IF gStopped THEN                {draw a red (or white) stop light}
  638.         ForeColor(redColor)
  639.     ELSE
  640.         ForeColor(whiteColor);
  641.     PaintOval(gStopRect);
  642.     ForeColor(blackColor);
  643.     FrameOval(gStopRect);
  644.     IF NOT gStopped THEN            {draw a green (or white) go light}
  645.         ForeColor(greenColor)
  646.     ELSE
  647.         ForeColor(whiteColor);
  648.     PaintOval(gGoRect);
  649.     ForeColor(blackColor);
  650.     FrameOval(gGoRect);
  651. END; {DrawWindow}
  652.  
  653.  
  654. {$S Main}
  655. PROCEDURE DoContentClick(window: WindowPtr; event: EventRecord);
  656.  
  657. {This is called when a mouse-down event occurs in the content of a window.
  658.  Other applications might want to call FindControl, TEClick, etc., to
  659.  further process the click.}
  660.  
  661. BEGIN
  662.     SetLight(window, NOT gStopped);
  663. END; {DoContentClick}
  664.  
  665.  
  666. {$S Main}
  667. PROCEDURE DoUpdate(window: WindowPtr);
  668.  
  669. {This is called when an update event is received for a window.
  670.  It calls DrawWindow to draw the contents of an application window.
  671.  As an effeciency measure that does not have to be followed, it
  672.  calls the drawing routine only if the visRgn is non-empty. This
  673.  will handle situations where calculations for drawing or drawing
  674.  itself is very time-consuming.}
  675.  
  676. BEGIN
  677.     IF IsAppWindow(window) THEN BEGIN
  678.         BeginUpdate(window);                    {sets up the visRgn, clears updateRgn}
  679.         IF NOT EmptyRgn(window^.visRgn) THEN    {draw if updating needs to be done}
  680.             DrawWindow(window);
  681.         EndUpdate(window);                        {restores the visRgn}
  682.     END;
  683. END; {DoUpdate}
  684.  
  685.  
  686. {$S Main}
  687. PROCEDURE DoActivate(window: WindowPtr; becomingActive: BOOLEAN);
  688.  
  689. {This is called when a window is activated or deactivated.
  690.  In Sample, the Window Manager's handling of activate and
  691.  deactivate events is sufficient. Other applications may have
  692.  TextEdit records, controls, lists, etc., to activate/deactivate.}
  693.  
  694. BEGIN
  695.     IF IsAppWindow(window) THEN
  696.         IF becomingActive THEN
  697.             {do whatever you need to at activation}
  698.         ELSE
  699.             {do whatever you need to at deactivation};
  700. END; {DoActivate}
  701.  
  702.  
  703. {$S Main}
  704. PROCEDURE GetGlobalMouse(VAR mouse: Point);
  705.  
  706. {Get the global coordinates of the mouse. When you call OSEventAvail
  707.  it will return either a pending event or a null event. In either case,
  708.  the where field of the event record will contain the current position
  709.  of the mouse in global coordinates and the modifiers field will reflect
  710.  the current state of the modifiers. Another way to get the global
  711.  coordinates is to call GetMouse and LocalToGlobal, but that requires
  712.  being sure that thePort is set to a valid port.}
  713.  
  714. VAR
  715.     event    : EventRecord;
  716.     
  717. BEGIN
  718.     IF OSEventAvail(kNoEvents, event) THEN;    {we aren't interested in any events}
  719.     mouse := event.where;                    {just the mouse position}
  720. END;
  721.  
  722.  
  723. {$S Main}
  724. PROCEDURE AdjustCursor(mouse: Point; region: RgnHandle);
  725.  
  726. {Change the cursor's shape, depending on its position. This also calculates the region
  727.  where the current cursor resides (for WaitNextEvent). If the mouse is ever outside of
  728.  that region, an event is generated, causing this routine to be called. This
  729.  allows us to change the region to the region the mouse is currently in. If
  730.  there is more to the event than just “the mouse moved”, we get called before the
  731.  event is processed to make sure the cursor is the right one. In any (ahem) event,
  732.  this is called again before we fall back into WNE.}
  733.  
  734.  
  735. VAR
  736.     window                : WindowPtr;
  737.     arrowRgn            : RgnHandle;
  738.     plusRgn                : RgnHandle;
  739.     globalPortRect        : Rect;
  740.     
  741.  
  742. BEGIN
  743.     window := FrontWindow;    {we only adjust the cursor when we are in front}
  744.     IF (NOT gInBackground) AND (NOT IsDAWindow(window)) THEN BEGIN
  745.         {calculate regions for different cursor shapes}
  746.         arrowRgn := NewRgn;
  747.         plusRgn := NewRgn;
  748.  
  749.         {start with a big, big rectangular region}
  750.         {1.01 - changed to kExtremeNeg and kExtremePos for consistency}
  751.         SetRectRgn(arrowRgn, kExtremeNeg, kExtremeNeg,
  752.                             kExtremePos, kExtremePos);
  753.  
  754.         {calculate plusRgn}
  755.         IF IsAppWindow(window) THEN BEGIN
  756.             SetPort(window);            {make a global version of the portRect}
  757.             SetOrigin(-window^.portBits.bounds.left, -window^.portBits.bounds.top);
  758.             globalPortRect := window^.portRect;
  759.             RectRgn(plusRgn, globalPortRect);
  760.             SectRgn(plusRgn, window^.visRgn, plusRgn);
  761.             SetOrigin(0, 0);
  762.         END;
  763.  
  764.         {subtract other regions from arrowRgn}
  765.         DiffRgn(arrowRgn, plusRgn, arrowRgn);
  766.  
  767.         {change the cursor and the region parameter}
  768.         IF PtInRgn(mouse, plusRgn) THEN BEGIN
  769.             SetCursor(GetCursor(plusCursor)^^);
  770.             CopyRgn(plusRgn, region);
  771.         END ELSE BEGIN
  772.             SetCursor(arrow);
  773.             CopyRgn(arrowRgn, region);
  774.         END;
  775.  
  776.         {get rid of our local regions}
  777.         DisposeRgn(arrowRgn);
  778.         DisposeRgn(plusRgn);
  779.     END;
  780. END; {AdjustCursor}
  781.  
  782.  
  783. {$S Main}
  784. PROCEDURE DoEvent(event: EventRecord);
  785.  
  786. {Do the right thing for an event. Determine what kind of event it is, and call
  787.  the appropriate routines.}
  788.  
  789. VAR
  790.     part, err    : INTEGER;
  791.     window        : WindowPtr;
  792.     hit            : BOOLEAN;
  793.     key            : CHAR;
  794.     aPoint        : Point;
  795.  
  796. BEGIN
  797.     CASE event.what OF
  798.         mouseDown: BEGIN
  799.             part := FindWindow(event.where, window);
  800.             CASE part OF
  801.                 inMenuBar: BEGIN            {process the menu command}
  802.                     AdjustMenus;
  803.                     DoMenuCommand(MenuSelect(event.where));
  804.                 END;
  805.                 inSysWindow:                {let the system handle the mouseDown}
  806.                     SystemClick(event, window);
  807.                 inContent:
  808.                     IF window <> FrontWindow THEN BEGIN
  809.                         SelectWindow(window);
  810.                         {DoEvent(event);}    {use this line for "do first click"}
  811.                     END ELSE
  812.                         DoContentClick(window, event);
  813.                 inDrag:                        {pass screenBits.bounds to get all gDevices}
  814.                     DragWindow(window, event.where, screenBits.bounds);
  815.                 inGrow:;
  816.                 inZoomIn, inZoomOut:;
  817.             END;
  818.         END;
  819.         keyDown, autoKey: BEGIN                {check for menukey equivalents}
  820.             key := CHR(BAnd(event.message, charCodeMask));
  821.             IF BAnd(event.modifiers, cmdKey) <> 0 THEN    {Command key down}
  822.                 IF event.what = keyDown THEN BEGIN
  823.                     AdjustMenus;            {enable/disable/check menu items properly}
  824.                     DoMenuCommand(MenuKey(key));
  825.                 END;
  826.         END;                                {call DoActivate with the window and...}
  827.         activateEvt:                        {TRUE for activate, FALSE for deactivate}
  828.             DoActivate(WindowPtr(event.message), BAnd(event.modifiers, activeFlag) <> 0);
  829.         updateEvt:                          {call DoUpdate with the window to update}
  830.             DoUpdate(WindowPtr(event.message));
  831.         {1.01 - It is not a bad idea to at least call DIBadMount in response
  832.          to a diskEvt, so that the user can format a floppy.}
  833.         diskEvt:
  834.             IF HiWrd(event.message) <> noErr THEN BEGIN
  835.                 SetPt(aPoint, kDILeft, kDITop);
  836.                 err := DIBadMount(aPoint, event.message);
  837.             END;
  838.         kOSEvent:
  839.             CASE BAnd(BRotL(event.message, 8), $FF) OF    {high byte of message}
  840.                 kSuspendResumeMessage: BEGIN
  841.                     gInBackground := BAnd(event.message, kResumeMask) = 0;
  842.                     DoActivate(FrontWindow, NOT gInBackground);
  843.                 END;
  844.             END;
  845.     END;
  846. END; {DoEvent}
  847.  
  848.  
  849. {$S Main}
  850. PROCEDURE EventLoop;
  851.  
  852. {Get events forever, and handle them by calling DoEvent.
  853.  Get the events by calling WaitNextEvent, if it's available, otherwise
  854.  by calling GetNextEvent. Also call AdjustCursor each time through the loop.}
  855.  
  856. VAR
  857.     cursorRgn    : RgnHandle;
  858.     gotEvent    : BOOLEAN;
  859.     event        : EventRecord;
  860.     mouse        : Point;
  861.  
  862. BEGIN
  863.     cursorRgn := NewRgn;                {we’ll pass WNE an empty region the 1st time thru}
  864.     REPEAT
  865.         IF gHasWaitNextEvent THEN BEGIN    {put us 'asleep' forever under MultiFinder}
  866.             GetGlobalMouse(mouse);        {since we might go to sleep}
  867.             AdjustCursor(mouse, cursorRgn);
  868.             gotEvent := WaitNextEvent(everyEvent, event, MAXLONGINT, cursorRgn);
  869.         END ELSE BEGIN
  870.             SystemTask;                    {must be called if using GetNextEvent}
  871.             gotEvent := GetNextEvent(everyEvent, event);
  872.         END;
  873.         IF gotEvent THEN BEGIN
  874.             AdjustCursor(event.where, cursorRgn);    {make sure we have the right cursor}
  875.             DoEvent(event);
  876.         END;
  877.         {If you are using modeless dialogs that have editText items,
  878.          you will want to call IsDialogEvent to give the caret a chance
  879.          to blink, even if WNE/GNE returned FALSE. However, check FrontWindow
  880.          for a non-NIL value before calling IsDialogEvent.}
  881.     UNTIL FALSE;                        {loop forever; we quit through an ExitToShell}
  882. END; {EventLoop}
  883.  
  884.  
  885. PROCEDURE _DataInit; EXTERNAL;
  886.  
  887. {This routine is part of the MPW runtime library. This external
  888.  reference to it is done so that we can unload its segment, %A5Init.}
  889.  
  890. {$S Main}
  891. BEGIN
  892.     UnloadSeg(@_DataInit);    {note that _DataInit must not be in Main!}
  893.     
  894.     {1.01 - call to ForceEnvirons removed}
  895.     {If you have stack requirements that differ from the default,
  896.      then you could use SetApplLimit to increase StackSpace at 
  897.      this point, before calling MaxApplZone.}
  898.      
  899.     MaxApplZone;            {expand the heap so code segments load at the top}
  900.  
  901.     Initialize;                {initialize the program}
  902.     UnloadSeg(@Initialize);    {note that Initialize must not be in Main!}
  903.  
  904.     EventLoop;                {call the main event loop}
  905. END.
  906.